<?php

namespace app\home\controller;

use think\Controller;
use think\Db;

class Auth extends Controller
{
    public function login()
    {

        if (request()->isAjax()) {

            $data = input('');
            // dump($data);
            // $vercode = $data['code'];
            // if (!captcha_check($vercode)) {
            //     $this->error('验证失败');
            //
            // }
            $phone = trim($data['phone']);
            $password = trim($data['password']);
            if (!$phone || !$password) {
                $this->error('数据异常');
            }

            $user = Db::name('user')->where('phone', $phone)->find();
            if (!$user || $user['status'] != 1) {
                $this->error('用户不存在 或状态异常');
            }
            if ($user['password'] != cmf_password($password)) {
                $this->error('验证失败');
            }
            session('uid', $user['id']);
            session('user', $user);
            $updata = [];
            $updata['last_time'] = time();
            $updata['last_ip'] = request()->ip();

            Db::name('user')->where('id', $user['id'])->update($updata);
            $this->success('认证成功');


        } else {
            return $this->fetch();
        }


    }


    public function mobileauth()
    {

        if (request()->isAjax()) {
            $data = input();
            $mobile = $data['phone'];
            $mobile_code = $data['code'];
            if (!$mobile || !$mobile_code) {
                $this->error('请输入手机号或验证码');
            }
            $res = Db::name('sms_code')->where('phone', $mobile)->find();

            if ($res) {
                //是否过期
                if ($res['createtime'] < (time() - 60 * 10)) {
                    $this->error('验证码过期');
                }
                if ($res['code'] != $mobile_code) {
                    $this->error('验证码错误');
                }
                $user = Db::name('user')->where('phone', $mobile)->find();
                session('uid', $user['id']);
                session('user', $user);
                $this->success('认证成功');

            } else {
                $this->error('验证码错误2');
            }


        }
    }

    public function sms()
    {
        $uid = session('uid');
        $phone = input('phone');

        if (!isMobileNum($phone)) {
            $this->error('手机号不正确');
        };

        // 判断是否存在
        $res = Db::name('dd_users')->where('uid',$uid)
            ->field('openid')
            ->find();
        if (!$res) {
            $this->error('手机号未认证');
        }

        $res = sendSms($phone);
        if ($res == 1) {
            $this->success('验证码发送成功');
        }
        $this->error('验证码发送失败');
    }


}


